<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/examine/msgBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="审批中心" :showBack="true"></cusHeaderVue>
		<view class="tabBox" :style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`}">
			<view class="tabLi" :class="tabIndex==0?'tabLiA':''" @click="chooseTab(0)">
				待处理
			</view>
			<view class="tabLi" :class="tabIndex==1?'tabLiA':''" @click="chooseTab(1)">
				已处理
			</view>
			<view class="tabLi" :class="tabIndex==2?'tabLiA':''" @click="chooseTab(2)">
				我发起的
			</view>
			<view class="tabLi" :class="tabIndex==3?'tabLiA':''" @click="chooseTab(3)">
				抄送我的
			</view>
		</view>
		<view class="inptBox">
			<image src="/static/home/searchIcon.png" mode=""></image>
			<input type="text" placeholder="请输入关键字搜索" placeholder-style="color: #BBC0CB;" v-model="keywords"
				@confirm="handleSearch" />
		</view>
		<scroll-view scroll-y="true" :style="{height: `calc(100vh - ${scrollerHeight} - 90rpx - 195rpx)`}"
			:refresher-enabled="true" :refresher-triggered="refreshing" @refresherrefresh="onRefresh"
			@scrolltolower="onLoadMore">
			<view class="scrollBox">
				<view v-for="(item,index) in listData" :key="item.id || index" class="boxLi" @click="toDetail(item)">
					<view class="boxTop">
						<view class="boxName">
							{{ item.name || '审批事项' }}
						</view>
						<u-icon name="arrow-right" color="#b7b6c3" size="15"></u-icon>
					</view>
					<!-- 显示发起人信息 - 优先从processInstance获取 -->
					<view class="boxTip">
						发起人：{{ item.processInstance?.startUser?.nickname || item.startUser?.nickname || '未知' }}
					</view>
					<!-- 显示审批类型 -->
					<view class="boxTip">
						类型：{{ item.processInstance?.name || item.name || '审批事项' }}
					</view>
					<!-- 显示时间信息 -->
					<view v-if="item.endTime" class="boxTip">
						结束时间：{{ formatDate(item.endTime) }}
					</view>
					<view v-if="item.startTime" class="boxTip">
						开始时间：{{ formatDate(item.startTime) }}
					</view>
					<view v-if="item.createTime" class="boxTip">
						消息时间：{{ formatDate(item.createTime) }}
					</view>
					<!-- 显示审批摘要信息 -->
					<view v-if="item.summary && item.summary.length > 0" class="boxTip">
						<view v-for="(field, idx) in item.summary" :key="idx" v-if="field && field.key && field.value">
							{{ field.key }}：{{ field.value }}
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view v-if="!loading && listData.length === 0" class="no-data">暂无数据</view>
				<!-- 加载中状态 -->
				<view v-if="loading && listData.length === 0" class="loading">加载中...</view>
				<!-- 上拉加载提示 -->
				<view v-if="listData.length > 0" class="load-more">
					{{ hasMore ? '上拉加载更多' : '没有更多了' }}
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		ref,
		nextTick
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import {
		GETTaskTodoPage,
		GETTaskDonePage,
		GETProcessInstanceMyPage,
		GETProcessInstanceCopyPage
	} from '@/api/interface.js';
	import {
		onShow
	} from '@dcloudio/uni-app';
	// 状态管理
	const scrollerHeight = ref('');
	const tabIndex = ref(0);
	const keywords = ref('');
	const listData = ref([]);
	const pageNo = ref(1);
	const pageSize = ref(10);
	const loading = ref(false);
	const refreshing = ref(false);
	const hasMore = ref(true);


	// 获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}

	// 切换tab
	const chooseTab = async (index) => {
		tabIndex.value = index;
		// 重置分页参数
		pageNo.value = 1;
		hasMore.value = true;
		// 重新加载数据
		await loadData(true);
	}

	// 加载数据
	const loadData = async (reset = false) => {
		if (loading.value || (!hasMore.value && !reset)) return;

		loading.value = true;
		try {
			let res;
			const params = {
				pageNo: reset ? 1 : pageNo.value,
				pageSize: pageSize.value,
				name: keywords.value.trim()
			};

			// 根据不同tab调用不同接口
			switch (tabIndex.value) {
				case 0:
					// 待处理
					res = await GETTaskTodoPage(params);
					break;
				case 1:
					// 已处理
					res = await GETTaskDonePage(params);
					break;
				case 2:
					// 我发起的
					res = await GETProcessInstanceMyPage(params);
					break;
				case 3:
					// 抄送我的
					res = await GETProcessInstanceCopyPage(params);
					break;
			}

			if (res.code === 0 && res.data) {
				const data = res.data.list || [];
				if (reset) {
					listData.value = data;
				} else {
					listData.value = [...listData.value, ...data];
				}

				// 判断是否还有更多数据
				hasMore.value = data.length === pageSize.value;
				// 更新页码
				if (hasMore.value) {
					pageNo.value += 1;
				}
			}
		} catch (error) {
			console.error('加载数据失败:', error);
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
			refreshing.value = false;
		}
	}

	// 下拉刷新
	const onRefresh = async () => {
		refreshing.value = true;
		pageNo.value = 1;
		hasMore.value = true;
		await loadData(true);
	}

	// 上拉加载更多
	const onLoadMore = async () => {
		if (!loading.value && hasMore.value) {
			await loadData();
		}
	}

	// 搜索
	const handleSearch = async () => {
		pageNo.value = 1;
		hasMore.value = true;
		await loadData(true);
	}

	// 跳转到详情页
	const toDetail = (item) => {
		// 根据不同tab类型传递正确的参数
		let url = '/pages/examine/examineXq';
		// 获取流程实例ID
		const processInstanceId = item.processInstanceId || item.id;
		// 获取任务ID（对于待处理和已处理，taskId就是item.id）
		const taskId = item.id; // taskId 来自item.id

		url += `?processInstanceId=${processInstanceId}&taskId=${taskId}`;

		// 如果有processDefinitionId也传递过去，便于详情页获取流程信息
		if (item.processDefinitionId) {
			url += `&processDefinitionId=${item.processDefinitionId}`;
		}

		// 审批员角色
		if(tabIndex.value == 0){
			url += `&role=1`;
		}

		uni.navigateTo({
			url: url
		});
	}

	// 格式化日期
	const formatDate = (timestamp) => {
		if (!timestamp) return '';
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	}
	onShow(async () => {
		await loadData(true);
	});
	// 初始化
	onLoad(async (options) => {
		getBarHeight();
		// 获取URL参数
		console.log('接收到的参数:', options);

		// 根据type参数设置tabIndex
		if (options.type) {
			switch (options.type) {
				case 'todo':
					tabIndex.value = 0;
					break;
				case 'done':
					tabIndex.value = 1;
					break;
				case 'my':
					tabIndex.value = 2;
					break;
				case 'copy':
					tabIndex.value = 3;
					break;
			}
		}

		// 根据searchType参数设置搜索关键词
		if (options.searchType) {
			switch (options.searchType) {
				case 'todo':
					keywords.value = '待处理';
					break;
				case 'done':
					keywords.value = '已处理';
					break;
				case 'my':
					keywords.value = '我发起的';
					break;
				case 'copy':
					keywords.value = '抄送我的';
					break;
			}
		}

		await nextTick();
		await loadData(true);
	});
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 740rpx;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.tabBox {
		display: flex;
		align-items: center;
		justify-content: space-around;
		height: 50rpx;

		.tabLi {
			font-size: 29.49rpx;
			font-weight: 400;
			color: #3F3F3F;
			position: relative;
		}

		.tabLiA {
			font-weight: 500;
			font-size: 29.49rpx;
			color: #000000;
		}

		.tabLiA::after {
			content: "";
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			bottom: -10rpx;
			flex: 1;
			width: 61.54rpx;
			height: 6.41rpx;
			border-radius: 3.21rpx 3.21rpx 3.21rpx 3.21rpx;
			background: linear-gradient(-90deg, #feaf38, #f98434);
		}
	}

	.inptBox {
		width: 705rpx;
		height: 70rpx;
		border-radius: 35.26rpx 35.26rpx 35.26rpx 35.26rpx;
		background: #ffffff;
		box-shadow: 0.64rpx 1.28rpx 13.46rpx 0 #e19a2e29;
		margin: 45rpx auto 0;
		display: flex;
		align-items: center;
		padding: 0 27rpx;
		box-sizing: border-box;
		margin-bottom: 19rpx;

		image {
			width: 30.13rpx;
			height: 30.13rpx;
		}

		input {
			flex: 1;
			font-weight: 400;
			font-size: 28.21rpx;

			margin-left: 12rpx;
		}
	}

	.scrollBox {
		.boxLi {
			width: 705rpx;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			margin: 0 auto 22rpx;
			padding: 37rpx 27rpx;
			box-sizing: border-box;
			box-shadow: 0.64rpx 1.28rpx 13.46rpx 0 #e19a2e29;

			.boxTop {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 14rpx;

				.boxName {
					font-weight: 500;
					font-size: 33.33rpx;
					color: #1C2027;
				}
			}

			.boxTip {
				color: #5a5964;
				font-weight: 400;
				font-size: 25.64rpx;
				line-height: 48.72rpx;
			}
		}

		/* 空状态样式 */
		.no-data {
			text-align: center;
			color: #999;
			font-size: 28.21rpx;
			padding: 100rpx 0;
		}

		/* 加载中样式 */
		.loading {
			text-align: center;
			color: #999;
			font-size: 28.21rpx;
			padding: 50rpx 0;
		}

		/* 上拉加载提示样式 */
		.load-more {
			text-align: center;
			color: #999;
			font-size: 25.64rpx;
			padding: 30rpx 0;
		}
	}
</style>